<template>
  <!-- <a-modal
    :visible="true"
    class="form-modal"
    fullscreen
    :closable="false"
    :esc-to-close="false"
    title-align="center"
    :body-style="{ padding: 0 }"
    @ok="submit"
    @cancel="cancel"
  > -->
  <ContentCard :padding="0">
    <template #header>
      <pageHeaderNew
        title="添加新员工"
        :bread-crumb="['人事', '人事管理', '新增员工']"
      ></pageHeaderNew>
    </template>
    <ConditionBox :padding="20" v-if="+route.query.progress !== 4">
      <template #left>
        <a-radio-group v-model="progress">
          <template v-for="item in progressList" :key="item.value">
            <a-radio :value="item.value"
              >{{ item.lable }}
              <!-- <template #radio="{ checked }">
                <a-space
                  align="start"
                  class="custom-radio-card"
                  :class="{ 'custom-radio-card-checked': checked }"
                >
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot" />
                  </div>
                  <div>
                    <div className="custom-radio-card-title">
                      {{ item.lable }}
                    </div>
                  </div>
                </a-space>
              </template> -->
            </a-radio>
          </template>
        </a-radio-group>
      </template>
    </ConditionBox>
    <!-- <a-divider /> -->
    <div class="business">
      <div
        class="subDetail"
        v-for="item in subDetail.controltotaShow"
        :key="(item.code as string)"
      >
        <div class="head">
          <div class="sub-title">
            <p class="icon"></p>
            {{ item.cnName }}
          </div>
          <!-- <div class="setting" @click="change">设置</div>import html2Canvas from "html2canvas"; -->
        </div>
        <a-divider></a-divider>
        <div style="padding: 0 20px; margin: auto">
          <a-form ref="HumanForm" :model="item.subRelDetail" autoLabelWidth>
            <a-row :gutter="100">
              <template v-for="(ele, index) in item?.subRelDetail" :key="index">
                <a-col :span="ele.span ? ele.span : 12">
                  <FormItem
                    :disabled="disabledControl.includes(ele?.ctlCode)"
                    :componentType="(ele?.ctlComponentType as string)"
                    :props="(ele?.props as any)"
                    :name="(ele?.ctlCnName as string)"
                    :required="(ele?.ctlRequired as any)"
                    v-model:values="ele.values"
                    :code="(ele?.ctlCode as any)"
                    :data="ele"
                  />
                </a-col>
              </template>
            </a-row>
          </a-form>
        </div>
      </div>
    </div>
  </ContentCard>
  <footer>
    <a-space>
      <a-button @click="cancel">取消</a-button>
      <a-button type="primary" @click="submit(false)">保存</a-button>
      <a-button type="primary" @click="submit(true)">保存并继续新增</a-button>
    </a-space>
  </footer>
  <!-- </a-modal> -->
  <!-- <tableModal
    @changeId="changeId"
    v-model:visible="visible"
    :data="templateData.data"
  /> -->
  <showHead
    :refresh="init"
    v-model:visible="headVisible"
    :data="settingControltotaShow"
  />
  <!-- <confirmAdd @updataNode="updataNode" v-model:visible="confirmAddShow" /> -->
</template>
<script setup lang="ts">
/**
 * 1、根据业务code从控件总集获取控件列表A渲染表单
 * 2、获取一份后端给的控件列表B（里面有后端生成的id等相关信息）
 * 3、把A的值复制到B中相同code的控件
 */
import clonedeep from 'lodash.clonedeep';
import {
  GetPeropleTemplate,
  GetManual,
  AddStaff,
  AddOnboarding,
  GetNum,
  PostPositionPersonnele,
  PostPeropleTemplateUse,
  AddNewStaff
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { CheckApplySign } from '@/apis/management/personnel/changeManagement/inductionManagement';
import { useRouter } from 'vue-router';
import { GetHumanTemplateList } from '@/apis/management/human/baseSetting/humanSetting';
import { GetBusinessModalData } from '@/apis/controltotal/index';
import confirmAdd from './confirmAdd.vue';
import * as controltotalType from '@/apis/controltotal/type';
import { Message } from '@arco-design/web-vue';
import FormItem from '@/components/DynamicFormsNew/RenderingForm/FormItem/index.vue';
import tableModal from './tableModal.vue';
import showHead from './showHead.vue';
import useControlFormStore from '@/store/controlForm';
const controlFormStore = useControlFormStore();
controlFormStore.fieldNames.componentType = 'ctlComponentType';
controlFormStore.fieldNames.labelName = 'ctlCnName';
const route = useRoute();
let sign = '', // 签名
  timeStamp = 0, // 签名有效时间戳
  isExpired = false; // 签名是否过了有效期

// 判断签名是否过期
// onMounted(async () => {
//   if (Reflect.ownKeys(route.query).length > 0) {
//     sign = (route.query.sign as string) || '';
//     timeStamp = +(route.query.timeStamp as string) || 0;
//     const res = await CheckApplySign({
//       sign,
//       timeStamp
//     });
//     isExpired = res ? false : true;
//   }
// });
// const HumanForm = ref();
const visible = ref(false);
const confirmAddShow = ref(true);
// 存储控件总集模板与租户初始化模板
const subDetail = reactive<any>({
  controltotadata: [], // 控件总集
  PeropleData: [], // 初始化模板
  controltotaShow: []
});

// 禁止输入的控件
const disabledControl = [
  'CDC80FC12D1DE43018D098E8322D0F966' // 工号
];
/**
 * 验证所有表单
 */
const validate = async () => {
  let flag = true;
  for (let index = HumanForm.value.length; index > 0; index--) {
    if (await HumanForm.value[index - 1].validate()) {
      //验证不通过
      flag = false;
    }
  }
  return flag;
};

const manualStatus = ref(0);
// 初始化数据
const init = async () => {
  await getTemplateUse();
  console.log('templateUseData', templateUseData);
  //TODO:工号待完成
  const manual = 1; // (await GetManual()).status;
  manualStatus.value = manual as number;
  subDetail.controltotadata.length = 0;
  subDetail.PeropleData.length = 0;
  subDetail.controltotaShow.length = 0;
  const res = await GetBusinessModalData({
    funcCode: 'SER_FUNCCB8F13997A7146DBA1ED92C9940EF4B4'
  });
  console.log(' res.funcCtlInfos?.children', res.funcCtlInfos?.children);
  res.funcCtlInfos?.children?.forEach((ele: any, index: any) => {
    if (index > 1) return;
    if (ele?.subDetail) {
      ele?.subDetail?.subRelDetail.forEach((item: any) => {
        item.props = JSON.parse(item.props as string);
        if (item?.ctlFieldName === 'jobNumber' && manual === 2) {
          // item.props = JSON.parse(item.props as string);
          item.props.placeholder = '自动生成工号';
          // item.props = JSON.stringify(item.props);
          item.disabled = true;
          item.required = 2;
        }
      });
      subDetail.controltotadata.push(ele?.subDetail);
    } else if (ele?.ctlDetail) {
      subDetail.controltotadata.push(ele?.ctlDetail);
    } else {
      Message.error('总集无数据');
    }
  });
  // 获取人员模板
  // const res2: any = await GetHumanTemplateList({ page: 1, size: 10 });
  // templateData.data = res2.content;
  // value.value = res2.content[0].name;
  // valueId.value = res2.content[0].id;
  // res2.content.forEach((ele: any) => {
  //   ele.key = ele.id;
  // });
  // 获取租户初始化模板
  // await GetPeropleTemplateData();
};
const router = useRouter();

// 选中的人员模板
const value = ref('');
// 选中的人员id
const valueId = ref(0);
// 存储人员模板数据
const templateData: any = reactive({ data: [] });
// 打开模板设置
const change = () => {
  headVisible.value = true;
};
const headVisible = ref(false);
// 选中人员模板回调事件
const changeId = (e: number) => {
  valueId.value = e;
  value.value = templateData.data.filter((ele: any) => ele.id === e)[0].name;
};

// 设置控件
const settingControltotaShow = computed(() => {
  subDetail.controltotaShow = [];
  if (subDetail.PeropleData && subDetail.PeropleData.length > 0) {
    const newData = clonedeep(subDetail.PeropleData);
    const showItem: string[] = [];
    const showObj: any[] = [];

    subDetail.PeropleData.forEach((ele: any) => {
      ele.componentModel.forEach((item: any) => {
        showObj[item.ctlCode] = item.id;
        item.show === 1 ? showItem.push(item.ctlCode) : null;
      });
    });

    subDetail.controltotadata.forEach((ele: any) => {
      ele.subRelDetail.forEach((item: any) => {
        item.id = showObj[item.ctlCode];
        if (showItem.indexOf(item.ctlCode) !== -1) {
          item.show = true;
        } else {
          item.show = false;
        }
      });
    });

    newData.forEach((ele: any) => {
      ele.componentModel.forEach((item: any) => {
        item.show === 1 ? (item.show = true) : (item.show = false);
      });
      ele.subRelDetail = ele.componentModel;
    });
    newData.forEach((ele: any, index: number) => {
      ele.subRelDetail.sort((a: any, b: any) => {
        return a.order - b.order;
      });
      subDetail.controltotadata[index].subRelDetail = ele.subRelDetail;
      subDetail.controltotaShow.push(ele);
    });
    return [];
  } else {
    subDetail.controltotadata?.forEach((ele: any) => {
      delete ele.id;
      ele.subRelDetail?.forEach((item: any) => {
        item.show = false;
      });
    });
    console.log('s--s-s--s-s-d0d0d00ds', 'sss');
    subDetail.controltotaShow = clonedeep(subDetail.controltotadata);

    return subDetail.controltotadata;
  }
});
let templateUseData: any = [];
const getTemplateUse = async () => {
  const res = await PostPeropleTemplateUse({ type: 1 });
  templateUseData = res || [];
  templateUseData?.forEach((item) => {
    item?.collectionModel?.forEach((collection) => {
      collection?.controlModel?.forEach((control) => {
        control.props = JSON.parse(control.props);
      });
    });
  });
  console.log('res', res);
};
// 获取租户初始化模板
// const GetPeropleTemplateData = async () => {
//   const res = await GetPeropleTemplate();
//   subDetail.PeropleData = res;
// };

// 入职方式
const updataNode = () => {
  data.personnelList[0].personnelInstitutionListModel.progress = progress.value; //选中新增方式 1:待入职 2:预入职 3:入职办理
};
const cancel = () => {
  router.back();
};
const progressList = Object.freeze([
  // { value: 1, lable: '新增到入职申请' },
  { value: 2, lable: '新增到待入职' },
  { value: 3, lable: '新增到预入职' },
  { value: 4, lable: '新增到花名册' } // 这里传4 因为同时要在花名册和入职办理列表里面同时显示
  // { value: 5, lable: '新增到入职' }
]);
let progress = ref(+route.query.progress || 2); //入职类型，1:入职申请 2:待入职 3:预入职 4入职办理 5入职
let data: any = {
  personnelList: [
    {
      personnelInstitutionListModel: {
        contractStatus: 1 // 合同状态默认1
      },
      personnelTemplateCtlValue: []
    }
  ]
};
// 提交
const submit = async (isContinueAdd = false) => {
  if (!(await validate())) return;
  updataNode();
  const { collectionModel } = templateUseData[0];
  // 扁平化控件列表
  collectionModel?.forEach((item: any) => {
    const { templateId, subCode } = item;
    item.controlModel?.forEach((ele: any) => {
      const { collectionId: subId, id: ctlId, ctlCode } = ele;

      data.personnelList[0].personnelTemplateCtlValue.push({
        ctlCode,
        ctlId,
        subCode,
        subId,
        templateId
      });
    });
  });
  let positionSequenceId = 0; //  部门id
  let datatempStaffNum = null, // 储存data里面的工号
    controlStaffNum = null; // 储存控件里面的工号，用于显示
  subDetail.controltotaShow?.forEach((item: any) => {
    item.subRelDetail?.forEach((ele: any) => {
      const ctlItem = data.personnelList[0].personnelTemplateCtlValue.find(
        (ctl: any) => ctl.ctlCode === ele.ctlCode
      );
      if (!ctlItem) return;
      ctlItem.ctlValue = ele.values ? `${ele.values}` : void 0;

      switch (ctlItem.ctlCode) {
        case 'C62B8DC31189847E0972B5D8F721404B1': // 姓名
          data.personnelList[0].personnelInstitutionListModel.name =
            ctlItem.ctlValue;
          data.personnelList[0].personnelInstitutionListModel.templateUseId =
            ctlItem.templateId;
          break;
        case 'C3384BE6E60C341D68B8180DA04A1C4E1': // 手机号
          data.personnelList[0].personnelInstitutionListModel.mobile =
            ctlItem.ctlValue;
          break;
        case 'CDA91C3B660FC46CBA7978E7031672229': // 邮箱
          data.personnelList[0].personnelInstitutionListModel.email =
            ctlItem.ctlValue;
          break;
        case 'C7341027925C943708F3AEF98703ECC47': // 职位
          if (ctlItem.ctlValue) {
            data.personnelList[0].personnelInstitutionListModel.positionId =
              Number(ctlItem.ctlValue);
          }
          break;
        case 'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC': // 职位层级
          if (ctlItem.ctlValue) {
            data.personnelList[0].personnelInstitutionListModel.positionLevel =
              Number(ctlItem.ctlValue);
          }
          break;
        case 'CA8ABCC1480744557B3014C3454465A7E': // 公司
          if (ctlItem.ctlValue) {
            data.personnelList[0].personnelInstitutionListModel.companyId =
              +ctlItem.ctlValue;
            positionSequenceId = Number(ctlItem.ctlValue);
          }
          break;
        case 'CED44AC9966904CD1AB546D309903727C': // 部门
          data.personnelList[0].personnelInstitutionListModel.departmentId =
            +ctlItem.ctlValue;
          break;
        case 'CECEBAA743F9B4160B40A5A3E78588712': // 直接上级id
          data.personnelList[0].personnelInstitutionListModel.superiorId =
            +ctlItem.ctlValue;
          break;
        case 'CC0D5415792B24BBCAD7DF5AB8A25A0AB': // 入职时间
          data.personnelList[0].personnelInstitutionListModel.entryTime =
            ctlItem.ctlValue;
          break;
        case 'CDC80FC12D1DE43018D098E8322D0F966': // 工号
          datatempStaffNum = ctlItem;
          controlStaffNum = ele;
          break;
        case 'CE009C2E2B542409D815F0D3D54FE0E2B': // 工作地点
          data.personnelList[0].personnelInstitutionListModel.workPlace =
            +ctlItem.ctlValue;
          break;
        default:
          break;
      }
    });
  });

  // 如果是入职办理或者是入职,生成工号并放入控件里面
  // if (progress.value === 4 || progress.value === 5) {
  //   datatempStaffNum.ctlValue = await GetNum({
  //     positionSequenceId
  //   });
  //   controlStaffNum.values = datatempStaffNum.ctlValue;
  // }

  // // 如果过了有效期则不能新增
  // if (!isExpired) {
  await AddNewStaff(data);
  data.personnelList[0].personnelTemplateCtlValue = [];
  // } else Message.error('已过有效期！请重新申请！');
  if (isContinueAdd) {
    init();
  } else {
    if (progress.value === 2) {
      router.push({
        name: 'WaitManagement'
      });
    } else if (progress.value === 3) {
      router.push({
        name: 'PreentryManagement'
      });
    } else if (progress.value === 4) {
      router.push({
        name: 'EntryManagement'
      });
    }
  }
};
init();
</script>
<style lang="less" scoped>
.arco-steps {
  width: 30%;
  margin: auto;
  margin-top: 20px;
}
.business {
  // width: 75%;
  // height: 60vh;
  // overf0ow: auto;
  padding: 0 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
  // margin: auto;
  .subDetail {
    width: 100%;
    .head {
      box-sizing: border-box;
      border-radius: 4px;
      width: 100%;
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 0 10px;
      // background-color: #e8f0ff;
      margin: 20px 0;
      .sub-title {
        display: flex;
        align-items: center;
        .icon {
          border-radius: 4px;
          width: 6px;
          height: 70%;
          background-color: #3d7eff;
          height: 20px;
          padding: 0;
          margin: 3px 0;
          margin-right: 10px;
        }
      }
      .setting {
        margin-left: 16px;
        color: #3d7eff;
        cursor: pointer;
      }
    }
  }
}
.head {
  box-sizing: border-box;
  border-radius: 4px;
  width: 100%;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  // padding: 10px;
  // background-color: #e8f0ff;
  // margin: 20px;
  .sub-title {
    display: flex;
    align-items: center;
    .icon {
      border-radius: 4px;
      width: 6px;
      height: 70%;
      background-color: #3d7eff;
      height: 20px;
      padding: 0;
      margin: 3px 0;
      margin-right: 10px;
    }
  }
  .setting {
    color: #3d7eff;
    cursor: pointer;
  }
}
.main {
  // width: 70%;
  // margin: auto;
  display: flex;
  align-items: center;
  p {
    padding: 0;
    margin: 20px;
  }
}
.btn-group {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  border-top: 2px solid #f8f8f8;
  box-shadow: 0px -6px 2px rgb(0 0 0 / 2%);
}
:deep(.arco-btn) {
  margin-right: 20px;
  width: 120px;
}
:deep(.arco-input-wrapper) {
  cursor: pointer;
  flex: 1;
}
.custom-radio-card {
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  width: 250px;
  box-sizing: border-box;
}

.custom-radio-card-mask {
  height: 14px;
  width: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 100%;
  border: 1px solid var(--color-border-2);
  box-sizing: border-box;
}

.custom-radio-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 100%;
}

.custom-radio-card-title {
  color: var(--color-text-1);
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
}

.custom-radio-card:hover,
.custom-radio-card-checked,
.custom-radio-card:hover .custom-radio-card-mask,
.custom-radio-card-checked .custom-radio-card-mask {
  border-color: rgb(var(--primary-6));
}

.custom-radio-card-checked {
  background-color: var(--color-primary-light-1);
}

.custom-radio-card:hover .custom-radio-card-title,
.custom-radio-card-checked .custom-radio-card-title {
  color: rgb(var(--primary-6));
}

.custom-radio-card-checked .custom-radio-card-mask-dot {
  background-color: rgb(var(--primary-6));
}

footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}
</style>
